package forum.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import forum.dao.SectionDao;
import forum.model.TopicListResult;
import forum.model.User;
import forum.service.TopicService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;

/**
 * @author haomin
 * @date 2022/06/30 17:16
 **/

@WebServlet("/topic-list.json")
public class TopicListJsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String sidString = req.getParameter("sid");
        // TODO: 参数合法性问题
        int sid = Integer.parseInt(sidString);

        User currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }

        // 浏览一次主贴页面，浏览次数加1
        new SectionDao().update(sid);

        TopicService topicService = new TopicService();
        TopicListResult result = topicService.topicListResult(currentUser,sid);


        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(jsonString);
    }
}